# -.- coding:utf-8 -.-
import requests
from bs4 import BeautifulSoup

class GithubLogin():
    def __init__(self):

        # get请求url，获取token
        self.github_login_url = 'https://github.com/login'
        # post url，用于登陆
        self.github_post_url = 'https://github.com/session'
        # get请求url，用于验证是否登陆成功
        self.github_profile_url = 'https://github.com/'
        #headers头部字段

        self.headers = {
            'Referer': 'https://github.com/',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36',
            'Host': 'github.com'
        }

        # 设置session
        self.session = requests.session()


    #获取authenticity_token
    def get_token(self):

        html = self.session.get(self.github_login_url).text
        soup = BeautifulSoup(html,'lxml')
        authenticity_token = soup.find_all(type="hidden")[1] .get('value')
        return authenticity_token


    #post 提交数据，模拟登陆
    def post_account(self,email,password):

        #登陆时表单提交参数
        data = {
            # 'commit' : 'Sign in',
            # 'utf8':'✓',
            'authenticity_token': self.get_token(),
            'login': email,
            'password': password,
        }

        self.session.post(self.github_post_url,data=data,headers=self.headers)


    #验证是否登陆成功，打印登陆名
    def IsLogin(self):

        html = self.session.get(self.github_profile_url).text
        soup = BeautifulSoup(html,'lxml')
        avatar = soup.find_all('img','avatar float-left mr-1')[0].get('alt')[1::]
        print(avatar)


if __name__ == "__main__":

    github = GithubLogin()
    github.post_account(email='你的邮箱',password='你的密码')
    github.IsLogin()


